import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '@/store';
import Track from './Track';
import { deleteTrack } from '@/services/track';
import { selectTracks, updateTracks } from '@/store/draftsSlice';
import { setCursorPosition, setPixelsPerSecond } from '@/store/timeline';
import '@/styles/Timeline.css';
import AddTracks from './AddTracks';
import { ITrack } from '@/store/types/track';
import { message } from 'antd';
import TimelineRuler from './TimelineRuler';
import { eventBus } from '@/utils';
import Cursor from './Cursor';

const Timeline: React.FC = () => {
    const draft = useSelector((state: RootState) => state.drafts);
    const originalTracks = selectTracks({ draft: draft }) || [];
    const dispatch = useDispatch();
    const cursorPosition = useSelector((state: RootState) => state.timeline.cursorPosition);
    // 获取总时长
    const totalDuration = useSelector((state: RootState) => state.timeline.totalDuration);
    const pixelsPerSecond = useSelector((state: RootState) => state.timeline.pixelsPerSecond);
    // 时间线总时长
    const totalTimelineWidth = () => {
        // 预留200px
        return (totalDuration / 1000) * pixelsPerSecond + 1000;
    };

    // 处理游标位置变化
    const handleCursorPositionChange = (newPosition: number) => {
        dispatch(setCursorPosition(newPosition));
    };

    useEffect(() => {
        // 接受事件 立马更新UI 而不是等后端返回
        const unsubscribeTrackAddedUi = eventBus.on('track:added:ui', (data) => {
            dispatch(updateTracks([...originalTracks, data]));
        });
        return () => {
            unsubscribeTrackAddedUi();
        };
    }, [originalTracks, dispatch]); // 添加依赖数组
    // 根据render_index重新排序轨道
    const tracks = React.useMemo(() => {
        const tracksWithRenderIndex: Array<{ track: ITrack; renderIndex: number }> = [];
        originalTracks.forEach((track: ITrack) => {
            if (track.segments && track.segments.length > 0) {
                // 获取第一个segment的render_index作为轨道的render_index
                console.log('track.segments', track.segments);
                const firstSegmentRenderIndex = track.segments[0].render_index;
                console.log('渲染层级', firstSegmentRenderIndex);
                // 检查同一轨道的所有segments是否有相同的render_index
                const allSameRenderIndex = track.segments.every((segment) => segment.render_index === firstSegmentRenderIndex);
                if (allSameRenderIndex) {
                    tracksWithRenderIndex.push({
                        track,
                        renderIndex: firstSegmentRenderIndex,
                    });
                } else {
                    // 如果render_index不一致，使用第一个segment的render_index
                    console.warn(`Track ${track.id} has inconsistent render_index values across segments`);
                    tracksWithRenderIndex.push({
                        track,
                        renderIndex: firstSegmentRenderIndex,
                    });
                }
            } else {
                // 如果没有segments，使用默认值0
                tracksWithRenderIndex.push({
                    track,
                    renderIndex: 0,
                });
            }
        });
        // 按render_index降序排序（值越大位置越靠上）
        return tracksWithRenderIndex.sort((a, b) => (b.renderIndex ? b.renderIndex :0) - (a.renderIndex ?a.renderIndex :0 ) ).map((item) => item.track);
    }, [originalTracks]);

    // 处理缩放级别变化
    const handlePixelsPerSecondChange = (value: number) => {
        dispatch(setPixelsPerSecond(value));
    };
    // 选中的轨道ID状态
    const [selectedTrackId, setSelectedTrackId] = useState<string | null>(null);
    // 右键菜单状态
    const [contextMenu, setContextMenu] = useState<{
        visible: boolean;
        x: number;
        y: number;
        track: ITrack | null;
    }>({
        visible: false,
        x: 0,
        y: 0,
        track: null,
    });

    // 轨道点击选中处理函数
    const handleTrackClick = (track: ITrack) => {
        // 切换选中状态：如果已选中则取消选中，否则选中
        setSelectedTrackId((prevId) => (prevId === track.id ? null : track.id));
    };

    // 轨道右键菜单处理函数
    const handleTrackContextMenu = (track: ITrack, event: React.MouseEvent) => {
        // 右键时自动选中轨道
        setSelectedTrackId(track.id);

        // 显示右键菜单
        setContextMenu({
            visible: true,
            x: event.clientX,
            y: event.clientY,
            track: track,
        });
    };

    // 关闭右键菜单
    const handleCloseContextMenu = () => {
        setContextMenu((prev) => ({ ...prev, visible: false, track: null }));
    };

    // 删除轨道处理函数
    const handleDeleteTrack = async (track: ITrack) => {
        try {
            if (!draft.draftId) {
                message.error('未找到当前草稿ID');
                return;
            }
            const track_to_delete = {
                draft_id: draft.draftId,
                track_id: track.id,
            };
            // UI层面先把这个轨道过滤掉 不展示 给用户更好的体验
            dispatch(updateTracks(tracks.filter((t) => t.id !== track.id)));
            deleteTrack(track_to_delete).then(() => {
                // 如果删除的是当前选中的轨道，清除选中状态
                if (selectedTrackId === track.id) {
                    setSelectedTrackId(null);
                }
                // 关闭右键菜单
                eventBus.emit('track:deleted', {
                    trackId: track.id,
                });
                message.success('轨道删除成功！');
            });
            handleCloseContextMenu();
        } catch (error: any) {
            message.error('删除轨道失败！', error.message);
        }
    };

    // 点击外部关闭菜单的处理
    useEffect(() => {
        // 点击其他地方关闭右键菜单
        const handleClickOutside = () => {
            if (contextMenu.visible) {
                handleCloseContextMenu();
            }
        };
        document.addEventListener('click', handleClickOutside);
        return () => {
            document.removeEventListener('click', handleClickOutside);
        };
    }, [contextMenu.visible]);

    return (
        <div className="timeline-container">
            {/* 时间线控制区 (例如：播放头、缩放按钮) */}
            <div className="timeline-controls">
                <div className="timeline-controls-content">
                    {/* 缩放控制器 */}
                    <div className="timeline-zoom-controls">
                        <input type="range" min="1" max="100" step="10" value={pixelsPerSecond} onChange={(e) => handlePixelsPerSecondChange(Number(e.target.value))} className="zoom-slider" />
                        <span className="zoom-label">{pixelsPerSecond}px/s</span>
                    </div>
                    {/* 左侧占位区域，与轨道头宽度一致 */}
                    <div className="timeline-left-spacer"></div>
                    {/* 时间轴刻度尺 - 与轨道内容区域对齐 */}
                    <TimelineRuler scale={pixelsPerSecond} zoom={1} start={0} duration={1000} width={totalTimelineWidth()} />
                </div>
            </div>

            {/* 时间线主区域：轨道列表 */}
            <div className="timeline-main-area">
                <div className="tracks-list">
                    <Cursor position={cursorPosition} isVisible={true} onPositionChange={handleCursorPositionChange} minPosition={200} maxPosition={3000} />
                    {tracks &&
                        tracks.map((track: ITrack) => (
                            <Track
                                key={track.id}
                                track={track}
                                pixelsPerSecond={pixelsPerSecond}
                                onClipDragStart={() => {}} // 传递拖拽开始处理函数
                                isSelected={selectedTrackId === track.id}
                                onClick={handleTrackClick}
                                onContextMenu={handleTrackContextMenu}
                            />
                        ))}
                </div>
            </div>

            {/* 添加轨道按钮区域 - 始终显示在轨道列表下方 */}
            <div className="add-tracks-section">
                <AddTracks />
            </div>

            {/* 右键菜单 */}
            {contextMenu.visible && contextMenu.track && (
                <div
                    style={{
                        position: 'fixed',
                        top: contextMenu.y,
                        left: contextMenu.x,
                        backgroundColor: '#2a2a2a',
                        border: '1px solid #444',
                        borderRadius: '4px',
                        padding: '4px 0',
                        zIndex: 1000,
                        minWidth: '120px',
                        boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
                    }}
                    onClick={(e) => e.stopPropagation()}
                >
                    <button
                        onClick={() => handleDeleteTrack(contextMenu.track!)}
                        style={{
                            width: '100%',
                            padding: '8px 16px',
                            border: 'none',
                            backgroundColor: 'transparent',
                            color: '#ff4d4f',
                            cursor: 'pointer',
                            textAlign: 'left',
                            fontSize: '13px',
                            transition: 'background-color 0.2s ease',
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = 'rgba(255, 77, 79, 0.1)';
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = 'transparent';
                        }}
                        title="删除轨道"
                    >
                        🗑️ 删除轨道
                    </button>
                </div>
            )}
        </div>
    );
};

export default Timeline;
